<?php
/**
 * Code for automatic input.
 * @author Ryley France <daedzealot@gmail.com>
 * @version 1.0
 * @since 2013-11-19
 */
require_once 'database.php';
require_once 'table.php';
require_once 'employees.php';
require_once 'materials.php';
require_once 'machines.php';
require_once 'customer.php';

loginInfo::update_login ();

/**
 * The main function for automatic input.
 *
 * @param type	The type of object that is being input.
 * @param file	The file name of the CSV file.
 * @return		Whether or not the update was successful.
 */
function automatic_input ($type, $file) {
	//name, phone_num, email, address

	$fp = fopen($file,'r');

	$csv_header = fgetcsv($fp);

	$db = new database();

	while($csv_line = fgetcsv($fp)) {
		$arr = array ();
		$j = count($csv_line);
		for ($i=0; $i<$j; $i++) {
			$arr[$csv_header[$i]] = $csv_line[$i];
		}

		$obj = new $type(0);
		$ret = $obj->init_from_post($arr);
		if (!$ret) {
			echo "The input file has errors in it.<br>\n";
			return FALSE;
		}

		$result = $obj->insert_to_database($db);
		// Check for error.
		if (!$result) {
			echo "There was an error when attempting to update the database.<br>\n";
			$db->close ();
			fclose ($fp);
			return FALSE;
		}
	}

	$db->close ();
	fclose ($fp);
	echo "File read successfully<br>\n";
}
?>
<html>
	<head>
		<title>Opol - Automatic Input</title>
	</head>
	<body>
		<link rel="stylesheet" type="text/css" href="opol.css">
		<?php require 'menu.php' ?>

<?php
if ($_POST) {
	$type = $_POST['type'];
	$file = $_FILES['filename']['tmp_name'];

	automatic_input ($type, $file);
}
?>

		<form action="" method="post" enctype="multipart/form-data">
			<table>
				<tr>
					<td><label>Type:</label></td>
					<td>
						<select name="type">
							<option value="machine">Machine</option>
							<option value="employee">Employee</option>
							<option value="customer">Customer</option>
							<option value="material">Material</option>
						</select>
					</td>
				</tr>
				<tr>
					<td><label>File:</label></td>
					<td><input type="file" name="filename"></td>
				</tr>
				<tr>
					<td><input type="submit" value="Go"></td>
				</tr>
			</table>
		</form>
	</body>
</html>
